<div class="tmd-doc">
<p></p>
<h1 class="tmd-header-1">
loop 2
</h1>
<p></p>
<div id="question" class="tmd-base">
<div class="tmd-usual">
What does the following program print?
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

func f() {
	var a = [2]int{5, 7}
	for i, v := range a {
		if i == 0 {
			a[1] = 9
		} else {
			print(v)
		}
	}
}

func g() {
	var a = [2]int{5, 7}
	for i, v := range a[:] {
		if i == 0 {
			a[1] = 9
		} else {
			print(v)
		}
	}
}

func main() {
	f()
	g()
}
</code></pre>
</div>
<p></p>
<div class="tmd-usual">
Choices:
</div>
<p></p>
<input type="radio" id="choiceA" name="choice" class="choice">
<input type="radio" id="choiceB" name="choice" class="choice">
<input type="radio" id="choiceC" name="choice" class="choice">
<input type="radio" id="choiceD" name="choice" class="choice">

<div id="choices">

<ul style="list-style-type:none;">
<li><label for="choiceA">77</label></li>
<li><label for="choiceB">79</label></li>
<li><label for="choiceC">97</label></li>
<li><label for="choiceD">99</label></li>
</ul>

</div><p></p>
<div id="answer" class="tmd-base">
<div class="tmd-usual">
Answer: 79
</div>
<p></p>
<div class="tmd-usual">
Run it on <a href="https://go.dev/play/p/gbS29WWWP3E">Go play</a>.
</div>
<p></p>
<div class="tmd-usual">
Key points:
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
When iterating the elements of a container (array/slice/map), the elements of a copy of the container is actually iterated.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
An array owns its elements. When copying an array, its elements are also copied. Modifying elements in an array doesn't affect the elements in the copy of the array.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
A slice just references its elements. When copying a slice (through assignment, not call the builtin <code class="tmd-code-span">copy</code> function), its elements are not copied. After copying, the copy of the slice shares elements with the original slice. So modifying elements in a slice means modifying the elements in the copy of the slice.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
So in function <code class="tmd-code-span">f</code>, the modification of <code class="tmd-code-span">a[1]</code> is not reflected in the loop. But the modification of <code class="tmd-code-span">a[1]</code> in function <code class="tmd-code-span">g</code> is reflected in the loop.
</div>
<p></p>
</div>
<p></p>
</div>
